package com.cs543.j.client.ui;

import com.cs543.j.client.MobileCloudClient;
import com.cs543.j.client.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView nameTextView;
	Button registerButton;

	boolean isPassed;

	@Override	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (getClientName() != null) {
			toClientList();
		}

		nameTextView = (TextView) this.findViewById(R.id.main_activity_name);
		registerButton = (Button) this.findViewById(R.id.main_activity_button);

		registerButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				setClientName(nameTextView.getText().toString());
				toClientList();
			}
		});
	}

	@Override
	protected void onResume() {

		if (isPassed) {
			this.finish();
		}

		super.onResume();
	}

	private void toClientList() {
		isPassed = true;
		MobileCloudClient.clientName = getClientName();
		Intent toRemote = new Intent(this, ClientListViewer.class);
		this.startActivity(toRemote);

		Thread t = new Thread(new Runnable() {

			public void run() {
				if (MobileCloudClient.clientName != null)
					MobileCloudClient.m_udpClient.register(MobileCloudClient.clientName);
			}
		});
		t.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void setClientName(String name) {
		SharedPreferences setting = this.getSharedPreferences("MobileCloud", 0);
		Editor editor = setting.edit();
		editor.putString("clientName", name);
		editor.commit();
	}

	public String getClientName() {
		SharedPreferences setting = this.getSharedPreferences("MobileCloud", 0);
		return setting.getString("clientName", null);
	}
}
